<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class upgrade_controller extends Controller {

	var $type = 'release';
	
	public function __construct() {
		parent::__construct();
		load_helper('global');
		$this->initi();
	}

	public function initi(){
		if($this->type=='release'){
			$version = config_item('pzrelease','version');
			$lockfile = BASEPATH.'data/upgrade'.$version.'.lock';
		}else{
			$lockfile = BASEPATH.'data/upgrade4.lock';
		}
		if(file_exists($lockfile)) {
			show_error("Puzzzing social has already upgraded!");
		}
		$this->language = config_item('language');
		$this->theme = 'upgrade';
		$this->thcolor = 'default';
	}
	public function render($tpl,$vars){
		return $this->template->display($tpl,$vars,$this->theme,$this->thcolor,true,0);
	}

	public function output($tpl,$vars=array(),$need_header_footer=true){
		$this->need_header_footer = $need_header_footer;
		$this->template->display($tpl,$vars,$this->theme,$this->thcolor,false,0);
	}

	public function mredirect($url,$message,$time=3){
		$this->template->display('common/message.htm',array('url'=>$url,'message'=>$message,'time'=>$time),$this->theme,$this->thcolor,false,0);
	}

	public function ajax_success_response($data,$message){
		$response = array('success' => true, 'data' => $data, 'message'=>$message);
		$content = json_encode($response);
		$this->template->content_display($content);
	}

	public function ajax_failed_response($message='failed_msg',$data=null){
		$response = array('success' => false,'message'=>$message,'data'=>$data);
		$content = json_encode($response);
		$this->template->content_display($content);
	}

	public function index(){
		$this->output("step1");
	}

	public function step2(){
		$env_check = array(
				'phpversion'=> array('label'=>'PHP Version',"need_version"=> '5.2.0',"curr_version"=>phpversion(),"check"=>true)
		);

		$func_check = array(
				'mysql_connect'=>array('label'=>'Mysql','check'=>false),
				'iconv'=>array('label'=>'ICONV','check'=>false),
				'gd_info'=>array('label'=>'GD','check'=>false),
				'json_encode'=>array('label'=>'JSON','check'=>false),
				'curl_init'=>array('label'=>'Curl','check'=>false),
				'puzz_run'=>array('label'=>'Puzzcore','check'=>false)
		);
		$dir_check = array(
				"data" => 					array("check"=>false,"attrib"=> 0),
				"data/attachments" => 		array("check"=>false,"attrib"=> 0),
				"data/template" => 		array("check"=>false,"attrib"=> 0),
				"data/group" => 		array("check"=>false,"attrib"=> 0),
				"data/topic" => 		array("check"=>false,"attrib"=> 0),
				"data/store" => 		array("check"=>false,"attrib"=> 0),
				"data/cache" => 		array("check"=>false,"attrib"=> 0),
				"config" => 		array("check"=>false,"attrib"=> 0),
				"logs" => 		array("check"=>false,"attrib"=> 0),
				//"config/database_default.php" => 		array("check"=>false,"attrib"=> 0),
		);
			
		$final_check = true;
		foreach($env_check as $key=>$value) {
			if (strnatcmp($env_check[$key]['curr_version'],$env_check[$key]['need_version']) < 0) {
				$env_check[$key]['check'] = false;
				$final_check = false;
			}
		}

		foreach($func_check as $key=>$value) {
			$func_check[$key]['check'] = function_exists($key);
			if (!$func_check[$key]['check']) $final_check = false;
		}

		foreach($dir_check as $key=>$value) {
			$dir_check[$key]['check'] = is_really_writable(BASEPATH.$key);
			if (!$dir_check[$key]['check']) $final_check = false;
		}

		$this->env_check = $env_check;
		$this->func_check = $func_check;
		$this->dir_check = $dir_check;
		$this->final_check = $final_check;

		$this->output("step2");
	}

	public function step3(){
		$this->output("step3");
	}
	public function param($key,$default=FALSE,$xss_clean = TRUE){
		$val = $this->input->get($key,$xss_clean);
		$val = (!$val&&!is_numeric($val))?$this->input->post($key,$xss_clean):$val;
		return ($val===false||$val==='')?$default:$val;
	}
	public function step4(){
		$db = load_db('upgrade');
		if($this->type=='release'){
			$version = config_item('pzrelease','version');
			$do_upgrade = $db->upgradeFromVersion();
			if($do_upgrade['status'] != 200) {
				$this->error = $do_upgrade;
			}else{
				$this->process();
			}
		}else{
			$do_upgrade = $db->upgradeFromFile();
			if($do_upgrade['status'] != 200) {
				$this->error = $do_upgrade;
			}else{
				$this->processimage();
			}
		}
	}
	
	public function process(){
		$page = $this->param("page",1);
		$numperpage = 100;
		$version = config_item('pzrelease','version');
		$api = load_api('upgrade/up'.$version);
		if($result = $api->execute($page,$numperpage)){
			$start=($page-1)*$numperpage;
			$end=$start+$numperpage;
			$str = "Processing {$start}----{$end}";
			$url = site_url('upgrade/process?page='.($page+1));
			$this->mredirect($url, $str, 2);
			return;
		}else{
			$lockfile = BASEPATH.'data/upgrade'.$version.'.lock';
			touch($lockfile);
			$url = site_url('admin/index');
			$this->mredirect($url, "升级成功，请前往后台更新缓存", 2000);
			return;
		}
		
	}

	public function processimage(){
		$page = $this->param("page",1);
		$ptx_item = load_db('share/item');
		$itemdetaildb = load_db('share/itemdetail');
		load_helper('file');
		$imagelib = &load_class('ImageLib');
		$attachmentdb = load_db('attachment');
		$items = $ptx_item->search(null,$page,100," ptx_item.user_id,ptx_item.image_path,ptx_item.img_pro,ptx_item.images_array,ptx_item.share_type,ptx_item.share_attribute,ptx_item.intro,ptx_item.intro_search,ptx_item.keyword,ptx_item.item_id,ptx_item.reference_url,ptx_item.reference_itemid,ptx_item.reference_channel,ptx_item.promotion_url ",NULL);
		foreach ($items as $item) {
			$data['item_id'] = $item['item_id'];
			$data['user_id'] = $item['user_id'];
			$itemdata=array();
			if($item['images_array']){
				$images = unserialize($item['images_array']);
				foreach ($images as $image){
					$imagelarge = rtrim(BASEPATH,'/').$image['url'].'_large.jpg';
					if(!$image['cover']&&!$itemdata['image_path_1']){
						$itemdata['image_path_1']=ltrim($image['url'],'/').'.jpg';
					}elseif(!$image['cover']&&!$itemdata['image_path_2']){
						$itemdata['image_path_2']=ltrim($image['url'],'/').'.jpg';
					}
					if(file_exists($imagelarge)){
						$imagepath = rtrim(BASEPATH,'/').$image['url'].'.jpg';
						@copy($imagelarge, $imagepath);
						$attachment = ltrim($image['url'],'/');
						$dest_file_path = BASEPATH.$attachment.'.jpg';
						$imagelib->crop_square($dest_file_path, 200);
						$info = get_file_info($imagepath);
						$pro = @getimagesize($imagepath);
						if($aid = $attachmentdb->addToAttachIndexTable($data)){
							$data['aid'] = $aid;
							$infornames = explode('/', $info['name']);
							$data['filename']=array_pop($infornames);
							$data['fileext']='jpg';
							$data['filesize']=$info['size'];
							$data['attachment']=$attachment;
							$data['description']=$image['desc'];
							$data['isimage'] = 1;
							$data['width'] = $pro['0'];
							$data['height'] = $pro['1'];
							if($image['cover']&&$item['share_type']=='video'&&$item['share_attribute']){
								$video = unserialize($item['share_attribute']);
								$data['remote'] = $video['video']['flv'];
								$data['description'] = $video['video']['title'];
								$data['source'] = $item['reference_url'];
								$data['isimage'] = 2;
							}
							
							$attachmentdb->addAttachByItem($item['item_id'],$data);
						}
					}
				}
			}
			$datadetail = array();
			$datadetail['item_id']=$item['item_id'];
			$datadetail['intro']=$item['intro'];
			$datadetail['intro_search']=$item['intro_search'];
			$datadetail['reference_url']=$item['reference_url'];
			$datadetail['reference_itemid']=$item['reference_itemid'];
			$datadetail['promotion_url']=pzxencode(str_replace('+', '%2B', $item['promotion_url']));
			$itemdetaildb->addone($datadetail);

			$keyword = str_replace('  ', ' ', $item['keyword']);
			if($keyword){
				$keywordarr = explode(' ', $keyword);
				$keyword_search = encodekeywords($keywordarr);
			}
			$plaintxt = load_api('puzzcode')->parse_plain_message($item['intro']);
			$itemdata['keyword_search']=$keyword_search;
			$itemdata['summary']=sysSubStr($plaintxt, 500, TRUE);
			if($item['image_path']){
				$itemdata['image_path_0']=ltrim($item['image_path'],'/').'.jpg';
				$path = BASEPATH.$itemdata['image_path_0'];
				$ipro = @getimagesize($path);
				$itemdata['width']=$ipro['0'];
				$itemdata['height']=$ipro['1'];
			}
			if($item['share_type']=='article'){
				$itemdata['item_type']='article';
				$itemdata['share_type']='upload';
			}elseif($item['share_type']=='video'){
				$itemdata['item_type']='video';
				$itemdata['share_type']='web';
			}else{
				if($item['share_type']=='channel'){
					$itemdata['share_type']='taobao';
				}elseif($item['reference_channel']&&$item['share_type']=='images'){
					$itemdata['share_type']='web';
				}else{
					$itemdata['share_type']='upload';
				}
				$itemdata['item_type']='image';
			}
			$ptx_item->update(array('item_id'=>$item['item_id']),$itemdata);
		}

		if(array_length($items)>0){
			$start=($page-1)*100;
			$end=$start+100;
			$str = "正在处理图片数据{$start}----{$end}";
			$url = site_url('upgrade/processimage?page='.($page+1));
			echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta http-equiv='refresh' content='2;url={$url}'></head><body>{$str}</body></html>";
			exit;
			return;
		}
		$url = site_url('upgrade/processUser');
		echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta http-equiv='refresh' content='2;url={$url}'></head><body>图片数据处理成功，正在进入下一步...</body></html>";
		exit;
	}
	

	public function processUser(){
		$page = $this->param("page",1);
		$usereb = load_db('user');
		$usergroupdb = load_db('user/user2usergroup');
		$users = $usereb->search(null,$page,100," ptx_user.* ",NULL);
		foreach ($users as $user) {
			if($user['user_type']=='3'){
				$usergroupdb->add_one(array('usergroup_id'=>1,'user_id'=>$user['user_id']));
				$usergroupdb->add_one(array('usergroup_id'=>8,'user_id'=>$user['user_id']));
			}elseif($user['user_type']=='2'){
				$usergroupdb->add_one(array('usergroup_id'=>2,'user_id'=>$user['user_id']));
				$usergroupdb->add_one(array('usergroup_id'=>8,'user_id'=>$user['user_id']));

			}elseif($user['user_type']=='0'){
				$usergroupdb->add_one(array('usergroup_id'=>4,'user_id'=>$user['user_id']));
				$usergroupdb->add_one(array('usergroup_id'=>8,'user_id'=>$user['user_id']));
			}else{
				$usergroupdb->add_one(array('usergroup_id'=>6,'user_id'=>$user['user_id']));
				$usergroupdb->add_one(array('usergroup_id'=>8,'user_id'=>$user['user_id']));
			}
		}
		if(array_length($users)>0){
			$start=($page-1)*100;
			$end=$start+100;
			$str = "正在处理用户数据{$start}----{$end}";
			$url = site_url('upgrade/processUser?page='.($page+1));
			echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta http-equiv='refresh' content='2;url={$url}'></head><body>{$str}</body></html>";
			exit;
			return;
		}
		$url = site_url('upgrade/step5');
		echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta http-equiv='refresh' content='2;url={$url}'></head><body>用户数据处理成功，正在进入下一步...</body></html>";
		exit;
	}

	public function step5(){
		$this->output("step5");
	}
	
	public function restoreShare(){
		$page = $this->param("page",1);
		$ptx_item = load_db('share/item');
		$itemdetaildb = load_db('share/itemdetail');
		$sharedb = load_db('share');
		$albumdb = load_db('album');
		$userb = load_db('user');
		$items = $ptx_item->search(null,$page,50," ptx_item.user_id,ptx_item.item_id,ptx_item.create_time ",NULL);
		foreach ($items as $item) {
			$shares = $sharedb->findAll(array('item_id'=>$item['item_id']));
			if(!$shares){
				$album = $albumdb->find(array('user_id'=>$item['user_id']));
				if(!$album){
					$album = array('user_id'=>$item['user_id'],'category_id'=>'5','album_title'=>'整容','create_time'=>$item['create_time']);
					$album['album_id']=$albumdb->create($album);
				}
				$user = $userb->find(array('user_id'=>$item['user_id']));
				$data['item_id'] = $item['item_id'];
				$data['user_id'] = $item['user_id'];
				$data['user_nickname'] = $user['nickname'];
				$data['poster_id'] = $item['user_id'];
				$data['poster_nickname'] = $user['nickname'];
				$data['album_id'] = $album['album_id'];
				$data['category_id'] = $album['category_id'];
				$data['create_time'] = $item['create_time'];
				//echo $item['item_id'].'-user-'.$item['user_id'].'-nick-'.$user['nickname'].'-cate-'.$album['category_id'].'-album_id-'.$album['album_id'].'-create_time-'.$item['create_time'].'\n<br/>';
				$sharedb->create($data);
			}
		}

		if(array_length($items)>0){
			$start=($page-1)*50;
			$end=$start+50;
			$str = "正在处理图片数据{$start}----{$end}";
			$url = site_url('upgrade/restoreShare?page='.($page+1));
			echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta http-equiv='refresh' content='10;url={$url}'></head><body>{$str}</body></html>";
			exit;
			return;
		}
		echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>图片数据处理成功</body></html>";
		exit;
	}

}